﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WeShare.WeiXin.Common;
using WeShare.WeiXin.Mp.Oauth.Entity;
using WeShare.WeiXin.Mp.UserManage.Entity;
#if !NET40
using System.Threading.Tasks;
#endif
using static WeShare.WeiXin.Common.OpenApi;
using static WeShare.WeiXin.Common.HttpUtil;
using TagsRes = WeShare.WeiXin.Mp.Oauth.Entity.TagsRes;

namespace WeShare.WeiXin.Mp.UserManage
{
    public class UserApi
    {
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="openid"></param>
        /// <param name="tokenOrAppId"></param>
        /// <param name="lang"></param>
        /// <returns></returns>
        public static UserInfo Get(string openid, string tokenOrAppId = "", string lang = "zh_CN")
        {
            var url = $"https://api.weixin.qq.com/cgi-bin/user/info?access_token={OpenApi.GetToken(tokenOrAppId)}&openid={openid}&lang={lang}";
            return HttpUtil.GetResult<UserInfo>(url);
        }
        public static OpenIdsRes GetOpenIds(string next_openid = "", string tokenOrAppId = "")
        {
            var url = $"https://api.weixin.qq.com/cgi-bin/user/get?access_token={OpenApi.GetToken(tokenOrAppId)}&next_openid={next_openid}";
            return HttpUtil.GetResult<OpenIdsRes>(url);
        }
        /// <summary>
        /// 创建标签
        /// </summary>
        /// <param name="name"></param>
        /// <param name="tokenOrAppId"></param>
        /// <returns></returns>
        public static BaseRes CreateTag(string name, string tokenOrAppId = "")
        {
            var url = $"https://api.weixin.qq.com/cgi-bin/tags/create?access_token={GetToken(tokenOrAppId)}";
            var data = new
            {
                tag = new { name = name }
            };
            return PostResult<BaseRes>(data, url);
        }

        public static TagsRes GetTags(string tokenOrAppId = "")
        {
            var url = $"https://api.weixin.qq.com/cgi-bin/tags/get?access_token={GetToken(tokenOrAppId)}";
            return GetResult<TagsRes>(url);
        }

        /// <summary>
        /// 更新标签
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <param name="tokenOrAppId"></param>
        /// <returns></returns>
        public static BaseRes UpdateTag(int id, string name, string tokenOrAppId = "")
        {
            var url =
                $"https://api.weixin.qq.com/cgi-bin/tags/update?access_token={GetToken(tokenOrAppId)}";
            var obj = new { tag = new { id = id, name = name } };
            return PostResult<BaseRes>(obj, url);
        }

        /// <summary>
        /// 删除标签
        /// </summary>
        /// <param name="id"></param>
        /// <param name="tokenOrAppId"></param>
        /// <returns></returns>
        public static BaseRes DeleteTag(int id, string tokenOrAppId = "")
        {
            var url = $"https://api.weixin.qq.com/cgi-bin/tags/delete?access_token={GetToken(tokenOrAppId)}";
            var obj = new { tag = new { id = id } };
            return PostResult<BaseRes>(obj, url);
        }

        /// <summary>
        /// 获取标签下的用户列表
        /// </summary>
        /// <param name="id"></param>
        /// <param name="nextOpenid"></param>
        /// <param name="tokenOrAppId"></param>
        /// <returns></returns>
        public static TagUsers GetTagUsers(int id, string nextOpenid = "", string tokenOrAppId = "")
        {
            var url = $"https://api.weixin.qq.com/cgi-bin/user/tag/get?access_token={GetToken(tokenOrAppId)}";
            var obj = new { tagid = id, next_openid = nextOpenid };
            var jobj = PostResult<JObject>(obj, url);
            var tagusers = new TagUsers();
            var errcode = jobj.GetValue("errcode");
            if (errcode == null)
            {
                tagusers.count = jobj.Value<int>("count");
                if (tagusers.count > 0)
                {
                    tagusers.next_openid = jobj.Value<string>("next_openid");
                    tagusers.openid = jobj["data"]["openid"].Select(r => r.Value<string>()).ToList();
                }
            }
            else
            {
                tagusers.errcode = errcode.Value<int>();
                tagusers.errmsg = jobj.Value<string>("errmsg");
            }
            return tagusers;
        }

        /// <summary>
        /// 批量为用户打标签
        /// </summary>
        /// <param name="openidList"></param>
        /// <param name="tagid"></param>
        /// <param name="tokenOrAppId"></param>
        /// <returns></returns>
        public static BaseRes BatchTagging(List<string> openidList, int tagid, string tokenOrAppId = "")
        {
            var url =
                $"https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token={GetToken(tokenOrAppId)}";
            var obj = new
            {
                openid_list = openidList,
                tagid = tagid
            };
            return PostResult<BaseRes>(obj, url);
        }

        /// <summary>
        /// 批量为用户取消标签
        /// </summary>
        /// <param name="openidList"></param>
        /// <param name="tagId"></param>
        /// <param name="tokenOrAppId"></param>
        /// <returns></returns>
        public static BaseRes BatchUnTagging(List<string> openidList, int tagId, string tokenOrAppId = "")
        {
            var url =
                $"https://api.weixin.qq.com/cgi-bin/tags/members/batchuntagging?access_token={GetToken(tokenOrAppId)}";
            var obj = new
            {
                openid_list = openidList,
                tagid = tagId
            };
            return PostResult<BaseRes>(obj, url);
        }

        /// <summary>
        /// 获取用户身上的标签列表
        /// </summary>
        /// <param name="openid"></param>
        /// <param name="tokenOrAppId"></param>
        /// <returns></returns>
        public static TagIds GetTagIdList(string openid, string tokenOrAppId = "")
        {
            var url = $"https://api.weixin.qq.com/cgi-bin/tags/getidlist?access_token={GetToken(tokenOrAppId)}";
            var obj = new { openid = openid };
            return PostResult<TagIds>(obj, url);
        }

        /// <summary>
        /// 更新用户备注
        /// </summary>
        /// <param name="openid"></param>
        /// <param name="remark"></param>
        /// <param name="tokenOrAppId"></param>
        /// <returns></returns>
        public static BaseRes UpdateRemark(string openid, string remark, string tokenOrAppId = "")
        {
            var url = $"https://api.weixin.qq.com/cgi-bin/user/info/updateremark?access_token={GetToken(tokenOrAppId)}";
            var obj = new { openid = openid, remark = remark };
            return PostResult<BaseRes>(obj, url);
        }

        /// <summary>
        /// 批量获取用户基本信息
        /// </summary>
        /// <param name="openids"></param>
        /// <param name="tokenOrAppId"></param>
        /// <returns></returns>
        public static BatchGetInfoRes BatchGetInfo(List<Openid> openids, string tokenOrAppId = "")
        {
            var url = $"https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token={GetToken(tokenOrAppId)}";
            return PostResult<BatchGetInfoRes>(new { user_list = openids }, url);
        }

        /// <summary>
        /// 获取关注用户的openid列表
        /// </summary>
        /// <param name="nextOpenid"></param>
        /// <param name="tokenOrAppId"></param>
        /// <returns></returns>
        

        /// <summary>
        /// 获取黑名单列表
        /// </summary>
        /// <param name="openId"></param>
        /// <param name="tokenOrAppId"></param>
        /// <returns></returns>
        public static UserOpenIdRes GetBlackList(string openId, string tokenOrAppId = "")
        {
            var url = $"https://api.weixin.qq.com/cgi-bin/tags/members/getblacklist?access_token={GetToken(tokenOrAppId)}";
            var data = new { begin_openid = openId };
            return PostResult<UserOpenIdRes>(data, url);
        }
        /// <summary>
        /// 批量添加进黑名单
        /// </summary>
        /// <param name="openIds"></param>
        /// <param name="tokenOrAppId"></param>
        /// <returns></returns>
        public static BaseRes BatchBlackList(List<string> openIds, string tokenOrAppId = "")
        {
            var url = $"https://api.weixin.qq.com/cgi-bin/tags/members/batchblacklist?access_token={GetToken(tokenOrAppId)}";
            var data = new { openid_list = openIds };

            return PostResult<BaseRes>(data, url);
        }

        /// <summary>
        /// 批量取消黑名单
        /// </summary>
        /// <param name="openIds"></param>
        /// <param name="tokenOrAppId"></param>
        /// <returns></returns>
        public static BaseRes BatchUnBlackList(List<string> openIds, string tokenOrAppId = "")
        {
            var url = $"https://api.weixin.qq.com/cgi-bin/tags/members/batchunblacklist?access_token={GetToken(tokenOrAppId)}";
            var data = new { openid_list = openIds };
            return PostResult<BaseRes>(data, url);
        }

#if !NET40
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="openid"></param>
        /// <param name="tokenOrAppId"></param>
        /// <param name="lang"></param>
        /// <returns></returns>
        public static async Task<UserInfo> GetAsync(string openid, string tokenOrAppId = "", string lang = "zh_CN")
        {
            var url = $"https://api.weixin.qq.com/cgi-bin/user/info?access_token={await OpenApi.GetTokenAsync(tokenOrAppId)}&openid={openid}&lang={lang}";
            return await HttpUtil.GetResultAsync<UserInfo>(url);
        }
        public static async Task<OpenIdsRes> GetOpenIdsAsync(string next_openid = "", string tokenOrAppId = "")
        {
            var url = $"https://api.weixin.qq.com/cgi-bin/user/get?access_token={await OpenApi.GetTokenAsync(tokenOrAppId)}&next_openid={next_openid}";
            return await HttpUtil.GetResultAsync<OpenIdsRes>(url);
        }
        /// <summary>
        /// 创建标签
        /// </summary>
        /// <param name="name"></param>
        /// <param name="tokenOrAppId"></param>
        /// <returns></returns>
        public static async Task<BaseRes> CreateTagAsync(string name, string tokenOrAppId = "")
        {
            var url = $"https://api.weixin.qq.com/cgi-bin/tags/create?access_token={await GetTokenAsync(tokenOrAppId)}";
            var data = new
            {
                tag = new { name = name }
            };
            return await PostResultAsync<BaseRes>(data, url);
        }

        public static async Task<TagsRes> GetTagsAsync(string tokenOrAppId = "")
        {
            var url = $"https://api.weixin.qq.com/cgi-bin/tags/get?access_token={await GetTokenAsync(tokenOrAppId)}";
            return await GetResultAsync<TagsRes>(url);
        }




        /// <summary>
        /// 更新标签
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <param name="tokenOrAppId"></param>
        /// <returns></returns>
        public static async Task<BaseRes> UpdateTagAsync(int id, string name, string tokenOrAppId = "")
        {
            var url =
                $"https://api.weixin.qq.com/cgi-bin/tags/update?access_token={await GetTokenAsync(tokenOrAppId)}";
            var obj = new { tag = new { id = id, name = name } };
            return await PostResultAsync<BaseRes>(obj, url);
        }

        /// <summary>
        /// 删除标签
        /// </summary>
        /// <param name="id"></param>
        /// <param name="tokenOrAppId"></param>
        /// <returns></returns>
        public static async Task<BaseRes> DeleteTagAsync(int id, string tokenOrAppId = "")
        {
            var url = $"https://api.weixin.qq.com/cgi-bin/tags/delete?access_token={await GetTokenAsync(tokenOrAppId)}";
            var obj = new { tag = new { id = id } };
            return await PostResultAsync<BaseRes>(obj, url);
        }

        /// <summary>
        /// 获取标签下的用户列表
        /// </summary>
        /// <param name="id"></param>
        /// <param name="nextOpenid"></param>
        /// <param name="tokenOrAppId"></param>
        /// <returns></returns>
        public static async Task<TagUsers> GetTagUsersAsync(int id, string nextOpenid = "", string tokenOrAppId = "")
        {
            var url = $"https://api.weixin.qq.com/cgi-bin/user/tag/get?access_token={await GetTokenAsync(tokenOrAppId)}";
            var obj = new { tagid = id, next_openid = nextOpenid };
            var jobj =await PostResultAsync<JObject>(obj, url);
            var tagusers = new TagUsers();
            var errcode = jobj.GetValue("errcode");
            if (errcode == null)
            {
                tagusers.count = jobj.Value<int>("count");
                if (tagusers.count > 0)
                {
                    tagusers.next_openid = jobj.Value<string>("next_openid");
                    tagusers.openid = jobj["data"]["openid"].Select(r => r.Value<string>()).ToList();
                }
            }
            else
            {
                tagusers.errcode = errcode.Value<int>();
                tagusers.errmsg = jobj.Value<string>("errmsg");
            }
            return tagusers;
        }

        /// <summary>
        /// 批量为用户打标签
        /// </summary>
        /// <param name="openidList"></param>
        /// <param name="tagid"></param>
        /// <param name="tokenOrAppId"></param>
        /// <returns></returns>
        public static async Task<BaseRes> BatchTaggingAsync(List<string> openidList, int tagid, string tokenOrAppId = "")
        {
            var url =
                $"https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token={await GetTokenAsync(tokenOrAppId)}";
            var obj = new
            {
                openid_list = openidList,
                tagid = tagid
            };
            return await PostResultAsync<BaseRes>(obj, url);
        }

        /// <summary>
        /// 批量为用户取消标签
        /// </summary>
        /// <param name="openidList"></param>
        /// <param name="tagId"></param>
        /// <param name="tokenOrAppId"></param>
        /// <returns></returns>
        public static async Task<BaseRes> BatchUnTaggingAsync(List<string> openidList, int tagId, string tokenOrAppId = "")
        {
            var url =
                $"https://api.weixin.qq.com/cgi-bin/tags/members/batchuntagging?access_token={await GetTokenAsync(tokenOrAppId)}";
            var obj = new
            {
                openid_list = openidList,
                tagid = tagId
            };
            return await PostResultAsync<BaseRes>(obj, url);
        }

        /// <summary>
        /// 获取用户身上的标签列表
        /// </summary>
        /// <param name="openid"></param>
        /// <param name="tokenOrAppId"></param>
        /// <returns></returns>
        public static async Task<TagIds> GetTagIdListAsync(string openid, string tokenOrAppId = "")
        {
            var url = $"https://api.weixin.qq.com/cgi-bin/tags/getidlist?access_token={await GetTokenAsync(tokenOrAppId)}";
            var obj = new { openid = openid };
            return await PostResultAsync<TagIds>(obj, url);
        }

        /// <summary>
        /// 更新用户备注
        /// </summary>
        /// <param name="openid"></param>
        /// <param name="remark"></param>
        /// <param name="tokenOrAppId"></param>
        /// <returns></returns>
        public static async Task<BaseRes> UpdateRemarkAsync(string openid, string remark, string tokenOrAppId = "")
        {
            var url = $"https://api.weixin.qq.com/cgi-bin/user/info/updateremark?access_token={await GetTokenAsync(tokenOrAppId)}";
            var obj = new { openid = openid, remark = remark };
            return await PostResultAsync<BaseRes>(obj, url);
        }

        /// <summary>
        /// 批量获取用户基本信息
        /// </summary>
        /// <param name="openids"></param>
        /// <param name="tokenOrAppId"></param>
        /// <returns></returns>
        public static async Task<BatchGetInfoRes> BatchGetInfoAsync(List<Openid> openids, string tokenOrAppId = "")
        {
            var url = $"https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token={await GetTokenAsync(tokenOrAppId)}";
            return await PostResultAsync<BatchGetInfoRes>(new { user_list = openids }, url);
        }

        /// <summary>
        /// 获取黑名单列表
        /// </summary>
        /// <param name="openId"></param>
        /// <param name="tokenOrAppId"></param>
        /// <returns></returns>
        public static async Task<UserOpenIdRes> GetBlackListAsync(string openId, string tokenOrAppId = "")
        {
            var url = $"https://api.weixin.qq.com/cgi-bin/tags/members/getblacklist?access_token={await GetTokenAsync(tokenOrAppId)}";
            var data = new { begin_openid = openId };
            return await PostResultAsync<UserOpenIdRes>(data, url);
        }
        /// <summary>
        /// 批量添加进黑名单
        /// </summary>
        /// <param name="openIds"></param>
        /// <param name="tokenOrAppId"></param>
        /// <returns></returns>
        public static async Task<BaseRes> BatchBlackListAsync(List<string> openIds, string tokenOrAppId = "")
        {
            var url = $"https://api.weixin.qq.com/cgi-bin/tags/members/batchblacklist?access_token={await GetTokenAsync(tokenOrAppId)}";
            var data = new { openid_list = openIds };

            return await PostResultAsync<BaseRes>(data, url);
        }

        /// <summary>
        /// 批量取消黑名单
        /// </summary>
        /// <param name="openIds"></param>
        /// <param name="tokenOrAppId"></param>
        /// <returns></returns>
        public static async Task<BaseRes> BatchUnBlackListAsync(List<string> openIds, string tokenOrAppId = "")
        {
            var url = $"https://api.weixin.qq.com/cgi-bin/tags/members/batchunblacklist?access_token={await GetTokenAsync(tokenOrAppId)}";
            var data = new { openid_list = openIds };
            return await PostResultAsync<BaseRes>(data, url);
        }

#endif
    }
}
